const express = require('express');
const router = express.Router();
const connection = require('../../config/database').production;
const knex = require('knex')(require('../../config/database').production);
const fs = require('fs');

// define the home page route
router.get('/', function (req, res) {
    res.send(`Yeah, I'm here. `+process.env.SERVICE_PORT);
});

router.get('/output/:message', function (req, res) {
    res.send(`params is: ` + req.params['message']);
});

router.post('/create/', function (req, res) {
    var body = JSON.stringify(req.body);
    knex('example')
        .insert({ name: Date.now().toString() })
        .then(function (rows) {
            res.send(`Body is: ` + body + '\r\nId is:' + rows[0]);
        })
        .catch(function (error) {
            res.status(500).send(error);
        });
});

router.put('/modify/:id', function (req, res) {
    var body = JSON.stringify(req.body);
    res.send(`ID is: ` + req.params['id'] + `\r\nBody is:` + body);
});

router.delete('/remove/:id', function (req, res) {
    res.send(`ID is: ` + req.params['id']);
});

var multer = require('multer');
var upload = multer({ dest: './uploads' })
var upload = multer({
    storage: multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, './uploads/');
        },
        filename: function (req, file, cb) {
            //file.originalname上传文件的原始文件名
            var changedName = new Date().getTime() + '-' + file.originalname;
            cb(null, changedName);
        },
    }),
    limits: {
        fileSize: 2 * 1024 * 1024,
    },
    fileFilter: function (req, file, cb) {
        console.log('filter')
        try {
            var ext = file.mimetype;
            console.log('mime: '+file.mimetype)
            if (ext == 'image/png') cb(null, true);
            else cb(null, false);
        } catch (error) {
            cb(new Error("upload file has some problem in filter process."));
        }
    },
});

router.post('/image/', upload.single('avatar'), function (req, res, next) {
    if (req.file == undefined)
        res.send('cannot get the file.');
    console.log(req.file);
    console.log(req.body);
    var file = req.file;
    console.log('MIME：%s', file.mimetype);
    console.log('originalName：%s', file.originalname);
    console.log('fileSize：%s', file.size);
    console.log('filePath：%s', file.path);
    res.send('Upload Complete!');
});

router.post('/images/', upload.array('photos', 12), function (req, res, next) {
    console.log(req.files);
    console.log(req.body);
    res.send('Upload Complete!');
});

router.get('/download/:filename', function (req, res) {
    const file = `./uploads/` + req.params['filename'];
    fs.stat(file, (err, stats) => {
        if (err) throw err;
        console.log(`stats: ${JSON.stringify(stats)}`);
        res.download(file); // Set disposition and send it.
    });
});

module.exports = router;
